<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="query.option" label="包含下级" />
      </el-form-item>
      <el-form-item label="策略名称:">
        <el-input v-model.trim="query.strategyName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="操作人:">
        <el-input v-model.trim="query.createUser" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" label="操作时间:" prop="transactTime">
        <el-date-picker
          v-model="query.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="true"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50503,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <sendOrdersTacticsDetail ref="sendOrdersTacticsDetail" />
  </div>
</template>

<script>
  import {
    queryMap,
    dispatchSettingLog
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import sendOrdersTacticsDetail from '../sendOrdersTactics/sendOrdersTacticsDetail'
  export default {
    name: '',
    components: { sendOrdersTacticsDetail },
    data() {
      return {
        treeData: [],
        operatorActionMap: [],
        query: {
          orgSNNo: null,
          timeRange: [],
          strategyName: '',
          createUser: '',
          createTimeStart: '',
          createTimeEnd: '',
          option: false
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'userInfo', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '操作',
            prop: 'operatorAction',
            render: (h, { row }) => (
            <span>{row.operatorAction ? formatColumnMap(this.operatorActionMap, 'value', row.operatorAction, 'desc') : ''}</span>
            )
          },
          {
            prop: 'strategyCode',
            label: '自动派单策略ID',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>{row.strategyCode}</el-link>
          )
          },
          { label: '策略名称', prop: 'strategyName' },
          { label: '所属机构', prop: 'orgName' },
          { label: '操作人', prop: 'createUser' },
          { label: '操作人所属机构', prop: 'operatorOrgName' },
          {
            label: '操作时间',
            prop: 'createTime',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          }
        ]
      }
    },
    async created() {
      this.getTreeData()
      await Promise.all([this.queryOptionsMap()])
      this.$nextTick(() => {
        this.$refs.lbTable.fetch()
      })
    },
    beforeDestroy() {
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.userInfo.orgSNNo
        this.query.orgId = this.userInfo.orgId
        this.query.orgName = this.userInfo.orgName
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'timeRange') {
                if (obj['timeRange'].length > 0) {
                  query['createTimeStart'] = parseTime(obj[key][0], '{y}-{m}-{d} {h}:{i}:{s}')
                  query['createTimeEnd'] = parseTime(obj[key][1], '{y}-{m}-{d} {h}:{i}:{s}')
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        const res = await dispatchSettingLog(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'DispatchSettingOperatorActionEnum' })
        ])
        this.operatorActionMap = res1.data // 派单策略枚举
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打开策略详情
      async openDetail(row) {
        await this.$refs.sendOrdersTacticsDetail.open(row)
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7) {
          return 'danger-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}
</style>
